using Consul;
using J.CustomerGet;
using J.CustomerGet.Extensions;
using J.Repository;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using NLog.Filters;
using NLog.Web;
using System.Reflection;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
//注入上下文
builder.Services.AddDbContext<MyDbContext>(x => x.UseSqlServer(builder.Configuration.GetConnectionString("ConnStr")));
//异常过滤器
builder.Host.UseNLog();
//全局异常过滤器
builder.Services.AddControllers(x => x.Filters.Add<MyExceptionFilter>());

//注入仓储服务
builder.Services.AssessGet();
//注入autoMapper
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
//注入中介者
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

///<summary>
///注册consul服务
///</summary>
static void RegisterConsul()
{
    var consulClient = new ConsulClient(p => { p.Address = new Uri($"http://10.31.56.23:8500"); });//请求注册的Consul地址（不动）
                                                                                                   //这里的这个ip就是本机的ip，这个端口8500这个是默认注册服务端口
    var httpCheck = new AgentServiceCheck()
    {
        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
        Interval = TimeSpan.FromSeconds(10),//间隔固定的时间访问一次，https://localhost:44308/api/Health
        HTTP = $"http://10.31.56.35:7776/WeatherForecast",//健康检查地址放（发布地址）WeatherForecast不要动就改ip加端口号
        Timeout = TimeSpan.FromSeconds(5)
    };

    var registration = new AgentServiceRegistration()
    {
        Checks = new[] { httpCheck },
        ID = Guid.NewGuid().ToString(),
        Name = "Customer(Read)",//服务名称项目名称
        Address = " http://10.31.56.35:7776/swagger/index.html",//改成发布地址
        Port = 7776,//服务端口（）
    };
    consulClient.Agent.ServiceRegister(registration).Wait();//注册服务
                                                            //consulClient.Agent.ServiceDeregister(registration.ID).Wait();//registration.ID是guid
                                                            //当服务停止时需要取消服务注册，不然，下次启动服务时，会再注册一个服务。
                                                            //但是，如果该服务长期不启动，那consul会自动删除这个服务，大约2，3分钟就会删了
}


builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
    string path = AppDomain.CurrentDomain.BaseDirectory + "J.Customer.xml";
    o.IncludeXmlComments(path, true);
});

//jwt
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //取出私钥
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["Authentication:Issuer"],
                        //验证接收者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["Authentication:Audience"],
                        // 验证是否过期
                        ValidateLifetime = true,
                        // 验证私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI();
//}
//跨域
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

app.UseStaticFiles();

app.UseAuthentication();//身份认证
app.UseAuthorization();//授权

app.MapControllers();
//注册consul服务
RegisterConsul();


app.Run();